package com.ruoyi.app.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.ServiceException;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.core.domain.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;

/**
 * @author 侯存路
 * @description
 * @since 2020/11/4 15:29
 */
@Api(value = "文件上传下载", tags = "文件相关接口")
@RestController
@RequestMapping("/api/file")
@Slf4j
public class FileController {


    @Value("${filepath}")
    private String filepath;

    /**
     * 处理文件上传
     */
    @PostMapping(value = "/upload")
    @ApiOperation("上传")
    public AjaxResult uploading(@RequestParam("file") MultipartFile multipartFile) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        Object path = LocalDate.now().getYear() +
                File.separator + LocalDate.now().getMonthValue() +
                File.separator + LocalDate.now().getDayOfMonth() +
                File.separator + UUID.randomUUID().toString() + suffixName;

        String filePath = filepath + path;
        System.out.println(filePath);
        try {
            File file = new File(filePath);
            file.getParentFile().mkdirs();//创建父级文件路径
            file.createNewFile();//创建文件
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("上传文件失败！");
        }
        return AjaxResult.success(path);
    }


    @GetMapping("/download")
    @ApiOperation("下载")
    @PassToken
    public void downLoad(HttpServletResponse response, @RequestParam("path") String path) throws UnsupportedEncodingException {
        String filePath = filepath + path;
        File file = new File(filePath);
        String filename = file.getName();
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
            byte[] buffer = new byte[1024];
            //输出流
            OutputStream os = null;
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
